<template>
	<view class="pad page page-top">
		<!-- <scroll-view scroll-y="true" :scroll-top="scrollTop" class="scroll-view" id="scrollView"> -->
		<view class="chat-box ">
			<image src="@/static/img/aislogo.png" class="avatar-img" mode=""></image>
			<view class="content-info">
				<view class="title font-24 c-6">
					小助手
				</view>
				<view class="say-content temp-content" style="padding-bottom:20rpx;">
					<view class="">
						您可以输入想绘画的内容，AI绘画助手一键为你生成。
					</view>
					<!--  <view class="rechange-box flex-row flex-end flex-align" @click="getHotQS">
						换一换 <image src="@/static/img/refresh.png" class="icon-refresh" mode=""></image>
					</view> -->
					<!-- <button class="btn primary mt-12" @click="maskVisible = true;">切换模型</button> -->
				</view>
			</view>
		</view>
		<view class="chat-box" :class="{'flex-end':item.self=== 1}" v-for="(item,index) in chatList" :key="item.id">
			<image :src="item.avatarImg" class="avatar-img" mode=""></image>
			<view class="content-info">
				<view class="title font-24 c-6">
					{{item.modelRole}}
				</view>
				<view class="say-content-box">
					<view class="say-content" :class="{'item-content':item.self === 0}"  style="background-color: #FFF;padding:20rpx;border-radius: 10rpx;">
						<text v-if="item.type==1" >{{item.content}}</text>
						<view class="img-content-box" v-else>

							<image :src="item.content" @load="imageLoading" class="content-image" mode="widthFix" ></image>
							<view class="loading-box" v-if="item.loading">
								<image src="@/static/img/loading.png" class="loading-img" mode=""></image>
							</view>
							<!-- <text >{{item.content}}</text> -->
						</view>
						
					</view>
				</view>
				<!-- <view class="mt-8 c-6 font-24" v-if="!item.loading && !item.self " @click="downLoadBtn(item.content)">
					下载图片
				</view> -->
			</view>
		</view>
		<!-- 选择模型 -->
		<view class="mask-box" v-show="maskVisible"></view>
		<view class="footer-margin"></view>
		<!-- </scroll-view> -->
		
		<view class="footer-input-box flex-row pad-30 flex-align" >
			<view class="footer-btns flex-row flex-end"> 
				<view class="btn primary"  @click="goPage('/pages/issureTmp/issureTmp')">
					问答助手
				</view>
				<view class="btn primary"   @click="goPage('/pages/user/recharge/recharge')">
					充值问答币
				</view>
			</view>
			<input type="text" v-model="content" class="form-input"  placeholder="请输入您的问题" placeholder-class="input-placeholder"/>
			<view class="send-btn btn primary flex-center" :class="{disabled:isConnect}" @click="sendBtn">
				发送
			</view>
		</view>
		
	</view>
</template>

<script setup>
	import {ref, reactive,nextTick  } from 'vue'
	import {	onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import { queryAiModel ,userInfo,cleanHistory, queryHotQs, drawImage } from '@/http/index.js'
	import { toast, copyContent } from '@/utils/tools.js'
	import env from '@/utils/env.js'
	import avatarDef from '@/static/img/avatar_deft.png'
	import aislogo from '@/static/img/aislogo.png'
	const modeArr = reactive([]), hotArray = reactive([]);
	let socketTask = null,isConnect = ref(false),scrollTop=ref(0),
		qsTimer = new Date().getTime();
	onLoad(()=>{
		let token = uni.getStorageSync('token');
		if(!token){
			// return uni.navigateTo({
			// 	url:'/pages/login/appLogin'
			// })
			// #ifdef APP-PLUS
				uni.redirectTo({
					//关闭当前页面，跳转到应用内的某个页面。
					url:'/pages/login/appLogin'
				});
			// #endif
			// #ifdef H5
				let ua = navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == "micromessenger"){
					//是
					uni.redirectTo({
						//关闭当前页面，跳转到应用内的某个页面。
						url:'/pages/login/login'
					});
				}else{
					//不是
					uni.redirectTo({
						//关闭当前页面，跳转到应用内的某个页面。
						url:'/pages/login/appLogin'
					});
				}
			// #endif
			// #ifdef MP-WEIXIN
				uni.redirectTo({
					//关闭当前页面，跳转到应用内的某个页面。
					url:'/pages/login/login'
				});
			// #endif
		}
		queryAiModel().then(res=>{
			modeArr.length = 0;
			res.data.map(it=>{
				it.modelContent = it.modelContent.replace('你','我');
			})
			modeArr.push(...res.data)
		})
		userInfo().then(res=>{
			let data = res.data;
			user.avatar = data.avatar||avatarDef;
			user.nickName = data.nickName;	
		})
		
		getHotQS()
		
		//创建链接
		
		
		
	})
	onShow(()=>{
		let token = uni.getStorageSync('token');
		if(!token){
			return uni.navigateTo({
				url:'/pages/login/appLogin'
			})
		}
		userInfo().then(res=>{
			let data = res.data;
			user.avatar = data.avatar||avatarDef;
			user.nickName = data.nickName;	
		})
	})
	
	onUnload(()=>{
		let token = uni.getStorageSync('token');
		uni.closeSocket({
			url: env.BASE_WS+'/api/websocket/'+token, 
			success:(res)=>{
				console.log('closeSocket success')
			}
		})
	})
	const tempBtn = (msg)=>{
		content.value = msg;
		sendBtn();
	}
	const goPage = (url)=>{
		uni.navigateTo({
			url:url
		})
	}
	const downLoadBtn = (linkUrl)=>{
		uni.showLoading({
						title: '加载中'
					});
					uni.downloadFile({
						url: linkUrl,
						success: (res) => {
							uni.hideLoading();
							if (res.statusCode === 200) {
								uni.saveImageToPhotosAlbum({
									filePath: res.tempFilePath,
									success: function() {
										uni.showToast({
											title: "保存成功",
											icon: "none"
										});
									},
									fail: function() {
										uni.showToast({
											title: "保存失败，请稍后重试",
											icon: "none"
										});
									}
								});
							}
						},
						fail:(err)=>{
							console.log('下载失败')
						}
			})
	}
	const user = reactive({
		nickName:'',
		avatar:'',
	})
	const aiUser = reactive({
		nickName:'小助手',
		avatar:aislogo,
	})
	const getHotQS = () =>{
		hotArray.length = 0;
		queryHotQs().then(res=>{
			if(res.data.length>3){
				res.data.length = 3
			}
			hotArray.push(...res.data);
		})
	}
	const copyContentBtn = (item)=>{
		copyContent(item);
	}
	const imageLoading = (data)=>{
		console.log('image load end')
		let lastItem = chatList[chatList.length - 1];
		// lastItem.type = 2;
		lastItem.loading = false;
		
	}
	const sendBtn = ()=>{
		console.log('send btn',isConnect.value);
		if(isConnect.value){ return; }
		if(!content.value){
			return toast("发送内容不能为空")
		}
		
		let data = {
			msg:content.value,
		}
		console.log(data)
		chatList.push({
			modelRole:user.nickName,
			avatarImg:user.avatar,
			self:1,
			type:1,
			id:+new Date(),
			content:content.value,
		})
		content.value = '';
		chatList.push({
			modelRole:aiUser.nickName,
			avatarImg:aiUser.avatar,
			self:0,
			type:1,
			id:+new Date(),
			content:'正在思考中...',
			loading:true,
		})
		drawImage(data).then(res=>{
			console.log('draw image',res.data.url)
			let data = res.data;
			if(/提问次数已用完/.test(data)){
				return toast("聊天次数已经用完")
			}
			if(new Date().getTime() - qsTimer>1.5e3){
				scrollBottom();
				qsTimer = new Date().getTime();
			}
			
			let lastItem = chatList[chatList.length - 1];
			lastItem.type = 2;
			lastItem.content = res.data.url;
			
			nextTick(()=>{
				scrollBottom();
			})
			
			
		})
	}
	
	function scrollBottom(){
		// console.log("scroll bottom")
		const query = uni.createSelectorQuery()
		query
			.select('.page-top')
			.boundingClientRect((data) => {
				let pageScrollTop = Math.round(data.bottom)
				uni.pageScrollTo({
					scrollTop: pageScrollTop, //滚动的距离
					duration: 0, //过渡时间
			})
		}).exec()
	}
	
	
	
	const chatList = reactive([]),modelId = ref('')
	const modelChoose = (data)=>{
		aiUser.avatar = data.modelImg;
		aiUser.nickName = data.modelTitle;

		maskVisible.value = false;
		let {modelImg:avatarImg, modelTitle:modelRole,modelCall:content,id} = data;
		modelId.value = id;
		chatList.push({
			avatarImg,
			modelRole,
			content,
			id:+ new Date(),
			self:	0,
		})
		//切换模型以后要调用接口清空上下文
		cleanHistory();
	}
	
	
	
	const content = ref('');
	//复制文本
	const copyBtn = ()=>{
		// #ifdef H5
		let textarea = document.createElement("textarea")
		textarea.value = textContent.value; 
		textarea.readOnly = "readOnly"
		document.body.appendChild(textarea)
		textarea.select() // 选中文本内容
		textarea.setSelectionRange(0, textContent.value.length) 
		uni.showToast({//提示
			title:'复制成功' ,
			icon:'success'
		})
		document.execCommand("copy") 
		textarea.remove();
		// #endif
		// #ifndef H5
		uni.setClipboardData({
		  data:this.textContent.value,//要被复制的内容
		  success:()=>{//复制成功的回调函数
			uni.showToast({//提示
			  title:`复制成功`,
			  icon:'success'
			})
		  }
		},true);
		// #endif
	}
	const maskVisible = ref(false)
		
	
</script>

<style lang="scss" scoped>
	.page{
		background-color: #F5F5F5;
		min-height:100vh;
		padding-top:30rpx;
	}
	.icon-refresh{
		height: 32rpx;
		width:32rpx;
		margin-left: 8rpx;
	}
	.content-image{
		width:450rpx;
		min-height: 450rpx;
	}
	.loading-box{
		height: 160rpx;
		padding-top:50rpx;
		position: absolute;
		left:0;
		top:0;
		width:450rpx;
		
		.loading-img{
			width: 60rpx;
			height: 60rpx;
			display: block;
			margin:0 auto;
			animation: circle 1s linear infinite;
		}
	}
	.img-content-box{
		position: relative;
	}
	.chat-box{
		display: flex;
		&+.chat-box{
			margin-top:20rpx;
		}
		@keyframes shine{
			0%{opacity: 1;}
			50%{opacity: .1;}
			0%{opacity: 1;}
		}
		.move-cursor{
			&::after{
				content:"|";
				animation: shine cubic-bezier(0.215, 0.610, 0.355, 1) 1s infinite;
			}
		}
		.avatar-img{
			width:90rpx;
			height:90rpx;
			border-radius: 50%;
			
			margin-right:12rpx;
		}
		.ques-tips{
			color:$theme-color;
			font-size: 26rpx;
			margin-top: 8rpx;
		}
		
		.temp-content{
			padding:20rpx;
			width:480rpx;
			border-radius: 12rpx;
			background-color: #FFF;
			line-height: 1.45;
			margin-top:8rpx;
		}
		
		&.flex-end{
			flex-direction: row-reverse;
			justify-content: flex-end;
			padding-left:104rpx;
			
			.title{
				text-align: right;
				width:480rpx;
			}
			.avatar-img{
				margin-left:12rpx;
				margin-right:0;
			}
			
			
			.say-content-box{
				margin-right:0;
				width:480rpx;
				display: flex;
				justify-content: flex-end;
				
				.say-content{

					padding:20rpx;
					max-width:480rpx;
					border-radius: 12rpx;
					background-color: #FFF;
					line-height: 1.45;
					margin-top:8rpx;
				}
				
			}
		}
		
	}
	.say-content.item-content{
		width:480rpx;
	}
	.footer-margin{
		height:230rpx;
	}
	.footer-input-box{
		position: fixed;
		bottom:0;
		left:0;
		width:100%;
		background-color: #FFFFFF;
		.form-input{
			flex:1;
			font-size: 28rpx;
		}
		.send-btn{
			width:140rpx;
			height: 66rpx;
			border-radius: 33rpx;
			display: flex;
			&.disabled{
				opacity: .5;
			}
		}
		.footer-btns{
			position: absolute;
			top: -80rpx;
			width:690rpx;
			.btn{
				font-size: 26rpx;
				line-height:60rpx;
				border-radius: 10rpx;
				&.btn{
					margin-left:12rpx;
				}
			}
		}
	}
	.scroll-view{
		height:calc(100vh - var(--top-window-height) - var(--tab-bar-height) )
	}
	.mask-box{
		width:100vw;
		height: 100vh;
		position: fixed;
		top:0;
		left:0;
		z-index: 12;
		background-color: rgba(0,0,0,.15);
		.mask-content{
			background-color: #FFFFFF;
			position: absolute;
			border-radius: 20rpx 20rpx 0 0;
			left:0;
			bottom: 0;
			width: 100vw;
			padding:30rpx 0;
		}
		.mask-title{
			text-align: center;
			position: relative;
			padding:0 30rpx;
			.icon-close{
				position: absolute;
				width: 32rpx;
				height: 32rpx;
				top:4rpx;
				right:32rpx;
			}
		}
		.mode-list{
			height: 500rpx;
			overflow-y: scroll;
			padding:0 30rpx;
			
			.mode-item{
				display: flex;
				// align-items: center;
				& + .mode-item{
					margin-top: 16rpx;
				}
				
				.icon-avatar{
					width:120rpx;
					height: 120rpx;
					border-radius: 10rpx;
					margin-right: 20rpx;
				}
				.mode-info{
					flex:1;
					height: 120rpx;
				}
				.mode-radio{
					margin-top:24rpx;
					background-color: $blue;
					height:60rpx;
					width:120rpx;
					color:#FFF;
					border-radius: 12rpx;
				}
			}
		}
	
	}

</style>
